<?php
/*************微信支付回调验证*************/
/*
 * 作用：将xml转为array
 * wj
 * 2016-09-29
 */
function xmlToArray($xml){
    //将XML转为array
    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $array_data;
}
/*
 * 作用：array转xml
 * wj
 * 2016-09-29
 */
function arrayToXml($arr){
    $xml = "<xml>";
    foreach ($arr as $key=>$val){
        if (1==1){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    return $xml;
}
/*
 * 验证参数的合法性
 */
function checkSign($arr){
    $tmpData = $arr;
    unset($tmpData['sign']);
    $sign = $this->create_sign($tmpData);//本地签名
    if ($arr['sign'] == $sign){
        return TRUE;
    }
    return FALSE;
}
/*
 *
 * 生成认证签名
 * create_time 2015-10-12
 * author wj
 */
function create_sign($data,$key){
    $tmpData = $data;
    unset($tmpData['sign']);
    $str ='';
    ksort($tmpData);//数组排序
    foreach($tmpData as $k=>$v){//拼接成相关规则的字符串
        if (!empty($v)){
            if ($str==''){
                $str =$k . "=" . $v ;
            }else{
                $str .='&'.$k . "=" . $v ;
            }
        }
    }
    $str .="&key=$key";
    //加密
    $str = MD5($str);
    $res = strtoupper($str);
    return $res;
}

/*
 * 检查微信回调返回数据的合法性
 * wj
 * 2016-09-29
 */
function checkWxReturn($xml,$key){
    $arr = xmlToArray($xml);
    if ($arr['return_code']=='SUCCESS' and $arr['result_code']=='SUCCESS') {//支付成功
        $sign = create_sign($arr,$key);
        if ($sign == $arr['sign']){
            $r_data['status'] = 1;
            $r_data['data'] = $arr;
            return $r_data;
        }else{
            $r_data['status'] = 0;
            $r_data['data'] = $arr;
            return $r_data;
        }
    }else{//支付失败
        $r_data['status'] = 0;
        $r_data['data'] = $arr;
        return $r_data;
    }
}

/**
 * 获取银行卡图标
 * @param $name 银行名称
 * @return mixed
 */
function get_bank_icon($name){
    $model = M('bank_icon');
    $map['name'] = array('like','%'.$name.'%');
    $icon_arr = $model->where($map)->find();
    if(empty($icon_arr)){
        unset($map);
        // $map['is_default'] = 1;
        $icon = $model->where($map)->getField('icon');
    }else{
        $icon = $model->where($map)->getField('icon');
    }
    return $icon;
}
